<template>
  <a-form
    ref="formRef"
    :model="formState"
    name="basic"
    layout="vertical"
    :hideRequiredMark="!!$route.params.id"
  >
    <FormItem
      v-for="item in formConfig"
      :key="item.key"
      :formItemConfig="item"
      :onlyRead="!!$route.params.id"
      v-model:formState="formState[item.key || '']"
    ></FormItem>
    <a-button v-if="!$route.params.id" type="primary" @click="handleSubmitClick"
      >提交</a-button
    >
  </a-form>
</template>
<script lang="ts" setup>
import { basicInfoForm } from "./config";
import FormItem from "@/components/Form/FormItem.vue";
import { getCurrentInstance, ref } from "vue";
import { createIndicatorSystem, getIndicatorSystemBasicInfo } from "@/api";
import { useRoute, useRouter } from "vue-router";
const { $loading } =
  getCurrentInstance()?.appContext?.config.globalProperties || {};
const route = useRoute();
const router = useRouter();
const formRef = ref();
const formConfig = !route.params.id
  ? basicInfoForm
  : basicInfoForm.filter((item) => item.key !== "fileId");
const formState = ref<Record<string, any>>({});
if (route.params.id) {
  $loading?.start();
  getIndicatorSystemBasicInfo(route.params.id as string)
    .then((res) => {
      formState.value = res;
    })
    .catch(console.error)
    .finally(() => $loading?.stop());
}
const handleSubmitClick = async () => {
  try {
    $loading?.start();
    const values = await formRef.value?.validate();
    const { fileId, ...rest } = values;
    const params = {
      fileId: fileId?.[0]?.id,
      ...rest,
    };
    await createIndicatorSystem(params);
    router.push("/indicators");
  } catch (e) {
    console.error(e);
  } finally {
    $loading?.stop();
  }
};
</script>
